package com.weex.app.hotreload;

import android.text.TextUtils;

import com.taobao.weex.utils.WXLogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Locale;

import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.ws.WebSocket;
import okhttp3.ws.WebSocketListener;
import okio.Buffer;

/**
 * @author kalaqia 421407393@qq.com
 */
public class MyWebSocketListener implements WebSocketListener {

    private WebSocket session;
    private HotReloadManager.ActionListener listener;


    public MyWebSocketListener(WebSocket session, HotReloadManager.ActionListener listener) {
        this.session = session;
        this.listener = listener;
    }

    public static final String TAG = MyWebSocketListener.class.getSimpleName();

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        WXLogUtils.w(TAG, "ws session open");
        session = webSocket;
    }

    @Override
    public void onFailure(IOException e, Response response) {
        e.printStackTrace();
    }

    @Override
    public void onMessage(ResponseBody message) throws IOException {
//        WXLogUtils.w(TAG, "on message");
//        if (payloadType == WebSocket.PayloadType.TEXT) {
//            String message = bufferedSource.readUtf8();
//            bufferedSource.close();
//            try {
//                JSONObject rpcMessage = new JSONObject(message);
//                String method = rpcMessage.optString("method", null);
//                if (!TextUtils.isEmpty(method)) {
//                    if ("WXReload".equals(method)) {
//                        listener.reload();
//                    } else if ("WXReloadBundle".equals(method)) {
//                        String bundleUrl = rpcMessage.optString("params", null);
//                        if (!TextUtils.isEmpty(bundleUrl)) {
//                            listener.render(bundleUrl);
//                        }
//                    }
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }
    }

    @Override
    public void onPong(Buffer payload) {
        WXLogUtils.w(TAG, "on pong");
    }

    @Override
    public void onClose(int code, String reason) {
        WXLogUtils.w("HotReloadManager", String.format(Locale.CHINESE, "Closed:%d,%s", code, reason));
    }
}
